package com.example.demo.service.impl;

import com.example.demo.entity.User;
import com.example.demo.dao.UserDao;
import com.example.demo.service.UserService;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2020-04-16 17:14:55
 */
@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;
    @Autowired
    SqlSessionTemplate sqlSessionTemplate;


    @Override
    public void insert(User user) {
        userDao.insert(user);
    }

    @Override
    public void insertBatch(List<User> users) {
        SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH,false);// 不自动提交
        try {
            UserDao dao = sqlSession.getMapper(UserDao.class);
            users.forEach(dao::insert);
            sqlSession.commit();
        }catch (Throwable e){
            e.printStackTrace();
            sqlSession.rollback();
        }finally {
            sqlSession.close();
        }

    }

    @Override
    @Transactional
    public Object sql(long currentTimeMillis) {
        Object sql = null;
        sql = this.userDao.sql(currentTimeMillis);
        return sql;
    }
}